local skynet = require "skynet"
require "skynet.manager"
local Hotfix = require "core.Hotfix"
local Module = require "core.Module"
local Service = require "core.Service"
local ServiceName = require "enum.ServiceName"
local lfs = require "lfs"
local Services = require "global.Services"

local script_name = ...

-- 全局变量，当前服务不需要热更的模块
HOT_FILTER_MODULE_LIST = {}
HOT_SCRIPT_NAME = script_name

skynet.register_protocol({
    id = skynet.PTYPE_HOTFIX,
    name = "hotfix",
    pack = skynet.pack,
    unpack = skynet.unpack,
    dispatch = function(session, source, hot_module_list)
        local hot_list = table.diff(hot_module_list, HOT_FILTER_MODULE_LIST)
        for i = 1, #hot_list do
            -- 热更模块
            local hot_module = hot_list[i]
            Hotfix.hotfix(hot_module)
        end
    end
})

local function initModuleService(mod)
    local modpath = Module.servicePath(mod, true)
    if modpath == script_name then
        return
    end

    -- 将模块 UniqueService 作为一个 Service 注册到 package.loaded 中，并且从热更模块中过滤
    package.loaded[modpath] = Service:new(ServiceName.getModuleName(mod))
    table.insert(HOT_FILTER_MODULE_LIST, modpath)
end

skynet.start(function()
    Services.HOT_MGR:register(skynet.self())

    table.foreach(Module.allServiceMod(), initModuleService)

    local instance = require(script_name)
    assert(type(instance) == "table", "module instance is not a table")
    if instance.init then
        instance.init()
    end

    if instance.listeners then
        local Eventer = require "core.Eventer"
        instance._receive = Eventer.receive
        local listeners = instance.listeners
        if type(instance.listeners) == "function" then
            listeners = instance.listeners()
        end

        Eventer.listenBatch(listeners)
    end
end)
